package com.meet.controller;

import com.meet.dao.UserDaoImpl;
import com.meet.dao.WorkersDao;
import com.meet.dao.WorkersDaoImpl;
import com.meet.entity.User;
import com.meet.entity.Workers;
import com.meet.service.WorkersService;
import com.meet.service.WorkersServiceImpl;
import com.meet.util.MD5Util;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

    private WorkersDao workersDao = new WorkersDaoImpl();
    private WorkersService workersService = new WorkersServiceImpl(workersDao);


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String flag=req.getParameter("flag");
        HttpSession session = req.getSession();
        System.out.println(flag);
        if("1".equals(flag)){

            String name = req.getParameter("user");
            String password = req.getParameter("password");

            User user = null;
            try {
                password= MD5Util.encryptMD5(password); //加密
                user = new UserDaoImpl().getUser(name,password);
            } catch (SQLException e) {
                e.printStackTrace();
                resp.sendRedirect("login.jsp");
                return;
            }
            //System.out.println(user);
            int id=user.getId();
            Workers workers=new Workers();
            workers.setId(id);
            workers.setUname(user.getName());
            System.out.println(workers);
            session.setAttribute("worker", workers);
            resp.sendRedirect("index.jsp");
            return;
        }else if("2".equals(flag)){
            session=req.getSession();
            session.invalidate();
            resp.sendRedirect("login.jsp");
            return;
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      //----------------------
        doGet(req, resp);



    }

}
